use salvo::{handler, Request};
use validator::Validate;
use crate::domain::dto::{parser_to_json, parser_to_res, rbatis_to_res, validation_to_json, PageRes, Res, ResObj};
use crate::domain::dto::project_dto::{ProjectCreateRequest, ProjectPageRequest, ProjectPageResponse, ProjectUpdateRequest};
use crate::domain::error::AccountError;
use crate::service::{project_service};

/// project_create 项目创建
#[handler]
pub async fn project_create(request: &mut Request) -> Res<bool> {
    let param = request.parse_json::<ProjectCreateRequest>()
        .await
        .map_err(|err| parser_to_json(err))?;

    let _ = param.validate().map_err(|err| validation_to_json(err))?;

    let res = project_service::project_create(param).await;
    rbatis_to_res(res)
}

/// project_update 项目更新
#[handler]
pub async fn project_update(request: &mut Request) -> Res<bool> {
    let param = request.parse_json::<ProjectUpdateRequest>()
        .await
        .map_err(|err| parser_to_json(err))?;
    // 验证
    let _ = param.validate().map_err(|err| validation_to_json(err))?;

    let res = project_service::project_update(param).await;
    rbatis_to_res(res)
}

/// app_add 项目删除
#[handler]
pub async fn project_delete(request: &mut Request) -> Res<bool> {
    let id_option = request.query::<u64>("id");
    if id_option.is_none() {
        return Err(ResObj::fail_with_error(AccountError::RequestError));
    }

    let res = project_service::project_delete(id_option.unwrap()).await;
    rbatis_to_res(res)
}

/// app_pages 项目分页
#[handler]
pub async fn project_pages(request: &mut Request) -> Res<PageRes<ProjectPageResponse>> {
    let mut param = request.parse_json::<ProjectPageRequest>()
        .await
        .map_err(|err| {
            tracing::error!("解析项目分页查询请求参数异常: {:?}", err);
            parser_to_json(err)
        })?;

    if param.page == None { param.page = Some(10) }
    if param.limit == None { param.limit = Some(1) }

    let res = project_service::project_pages(param).await;
    rbatis_to_res(res)
}